<!DOCTYPE HTML>
<html>
<head>
<title>XNR Background</title>
<script>

var albumInfos = {};

safari.application.addEventListener("message",function(msg) {
	switch(msg.name) {
		case "xnr_save":
			localStorage.setItem("xnr_options",msg.message);
			break;
		case "xnr_load":
			var options=localStorage.getItem("xnr_options");
			if(options==null) {
				msg.target.page.dispatchMessage("xnr_load_data",{id:msg.message,data:{}});
			} else {
				try {
					msg.target.page.dispatchMessage("xnr_load_data",{id:msg.message,data:JSON.parse(options)});
				} catch(ex) {
					msg.target.page.dispatchMessage("xnr_load_data",{id:msg.message,data:{}});
				}
			}
			break;
		case "xnr_storage":
			if (msg.message.data) {
				localStorage.setItem(msg.message.pref,msg.message.data);
			} else {
				var data=localStorage.getItem(msg.message.pref);
				msg.target.page.dispatchMessage("xnr_storage_resp",{id:msg.message.id,data:data});
			}
			break;
		case "xnr_get":
			var httpReq=new XMLHttpRequest();
			httpReq.onload=function() {
				if (httpReq.readyState == 4) {
					msg.target.page.dispatchMessage("xnr_get_data",{id:msg.message.id,data:(httpReq.status==200?httpReq.responseText:null)});
				}
			};
			httpReq.onerror=function(e) {
				msg.target.page.dispatchMessage("xnr_get_data",{id:msg.message.id,data:null});
			};
			httpReq.open(msg.message.method,msg.message.url,true);
			//httpReq.setRequestHeader("Cache-Control","no-cache");
			httpReq.send();
			break;
		case "xnr_album":
			do {
				var token = Math.floor(Math.random() * 100000);
			} while(token in albumInfos);
			albumInfos[token] = msg.message;
			var tab=safari.application.activeBrowserWindow.openTab();
			tab.url=safari.extension.baseURI+"album.html#" + token;
			break;
		case "xnr_getAlbumInfo":
			token = parseInt(msg.message);
			msg.target.page.dispatchMessage("albumInfo", albumInfos[token]);
			delete albumInfos[token];
			break;
	}
},false);
</script>
</head>
<body>
</body>
</html>
